package com.haiheng.module_main.fragment

import android.annotation.SuppressLint
import android.app.ScansManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.haiheng.common.dialog.StandardDialog
import com.haiheng.common.fragment.RouterFragment
import com.haiheng.library_base.adapter.BaseAdapter
import com.haiheng.library_base.dialog.LoadingDialog
import com.haiheng.library_base.model.ApplicationViewModel
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.msg.MsgCode
import com.haiheng.library_base.msg.MsgEvent
import com.haiheng.library_base.toast.ToastUtils
import com.haiheng.library_base.utils.FastClickUtil
import com.haiheng.module_main.R
import com.haiheng.module_main.adapter.BookListAdapter
import com.haiheng.module_main.databinding.FragmentBookOffShelvingBinding
import com.haiheng.module_main.mode.BookInfoViewModel
import com.haiheng.module_main.mode.DeploymentViewModel
import kotlinx.coroutines.launch

/**
 *
 * @Des:图书倒架
 * @Author: hwz
 * @Date:2023/6/17 0017
 * @Version: 1.0
 */
class BookOffShelvingFragment :RouterFragment() {
    private lateinit var binding: FragmentBookOffShelvingBinding
    private val viewMode : BookInfoViewModel by viewModels()
    private lateinit var deploymentViewModel: DeploymentViewModel
    private val bookListAdapter = BookListAdapter()
    val NON_EXTRA = 0 //无
    val ENTER_EXTRA = 1 //添加回车
    val BROADCAST_INPUT_MODE = 0 //广播模式
    val INPUTTEXT_INPUT_MODE = 1 //输入框模式
    private var inputmode: Int =INPUTTEXT_INPUT_MODE
    private var addExtra = NON_EXTRA
    private var mScansManager: ScansManager? = null
    //    private var broadcastReceiver: ScansReceiver? = null
    private lateinit var loadingDialog : LoadingDialog
    private var layerInfoSureDialog  : StandardDialog? = null
    private var srcContainerSubId :Int = 0
    private var newContainerSubId :Int = 0


    private val observer = Observer<MsgEvent> { msgEvent ->
        onMessageChange(msgEvent)
    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentBookOffShelvingBinding.inflate(inflater, container, false)
        return binding.root
    }
    override fun initView() {
        deploymentViewModel = DeploymentViewModel(viewMode)
        loadingDialog = LoadingDialog(requireContext(), R.style.AvLoadingDialogStyle)
        binding.includeTile.rbTitleLeft.setText("单册倒架")
        binding.includeTile.rbTitleRigh.setText("整层倒架")
        binding.includeBottom.btnSubmit.setText("倒架")
        binding.includeTile.ivBack.setOnClickListener {
            activity.navigateUp()
        }
        binding.includeTile.rbTitleRigh.performClick()
        binding.includeTile.rbTitleLeft.performClick()
        binding?.rvBookList?.layoutManager = LinearLayoutManager(activity)
        binding?.rvBookList?.adapter = bookListAdapter
        initLisener()
        changeViewStatus(true)
    }

    private fun initLisener() {
        binding.includeTile.cbRignt.setOnClickListener {
            binding.includeTile.cbRignt.isChecked = true
            binding.cbGetShelfNo.isChecked = false
        }
        binding.cbGetShelfNo.setOnClickListener {
            binding.includeTile.cbRignt.isChecked = false
            binding.cbGetShelfNo.isChecked = true
        }
        bookListAdapter.setOnItemClickListener(object : BaseAdapter.OnItemClickListener{
            override fun onItemClick(holder: BaseAdapter.ViewBindHolder, position: Int) {
                var bookInfoBean = bookListAdapter.getItem(position)
                bookInfoBean.isSelect = !bookInfoBean.isSelect
                var isAllSelet = true
                for (b in bookListAdapter.getData()){
                    if (!b.isSelect){
                        isAllSelet = false
                        break
                    }
                }
                binding.includeBottom.cbAll.isChecked = isAllSelet
                bookListAdapter.notifyDataSetChanged()
            }
        })
        binding.includeBottom.cbAll.setOnClickListener {
            for (b in viewMode._bookListData.value!!){
                b.isSelect = binding.includeBottom.cbAll.isChecked
            }
            bookListAdapter.notifyDataSetChanged()
        }
        binding.includeBottom.btnSubmit.setOnClickListener {//倒架
            if (binding.includeTile.rbTitleLeft.isChecked){
                //单册倒架
                var layNo = binding.includeIdentifyShelf.etTargetLocation.text
                if (layNo.isNotBlank()){
                    loadingDialog.setMessage(getString(R.string.text_book_off_ing))
                    loadingDialog.show()
                    deploymentViewModel.bookAssetLocation(layNo.toString())
                }else{
                    ToastUtils.showShort("层架号不能为空")
                }
            }else{
                //整层倒架
                var srcNo = binding.includeIdentifyShelf.etSouceShelfNo.text
                var newNo = binding.includeIdentifyShelf.etTargetLocation.text
                if (srcNo.isNullOrEmpty()){
                    ToastUtils.showShort("来源层架不能为空")
                    return@setOnClickListener
                }
                if (newNo.isNullOrEmpty()){
                    ToastUtils.showShort("目标层架不能为空")
                    return@setOnClickListener
                }
                if (srcNo.equals(newNo)){
                    ToastUtils.showShort("来源层架和目标不能是同一个")
                    return@setOnClickListener
                }
                deploymentViewModel.bookShifting(srcContainerSubId,newContainerSubId)

            }

        }
        binding.includeBottom.btnClear.setOnClickListener {
            if (binding.includeTile.rbTitleLeft.isChecked){
                viewMode._bookListData.postValue(listOf())
                bookListAdapter.getData().clear()
                bookListAdapter.notifyDataSetChanged()
            }else{
                binding.includeIdentifyShelf.tvSouceShelfName.setText("")
                binding.includeIdentifyShelf.etSouceShelfNo.setText("")
                binding.includeIdentifyShelf.tvTargetShelfName.setText("")
                binding.includeIdentifyShelf.etTargetLocation.setText("")
            }

        }

        binding.includeIdentifyShelf.etSouceShelfNo.setOnEditorActionListener {  v, keyCode, event ->
            if(keyCode == EditorInfo.IME_ACTION_SEARCH) {
                binding.includeIdentifyShelf.tvSouceShelfName.text = ""
                viewMode.getShelName(binding.includeIdentifyShelf.etSouceShelfNo.text.toString())
                false
            }
            false
        }
        binding.includeIdentifyShelf.etTargetLocation.setOnEditorActionListener {  v, keyCode, event ->
            if(keyCode == EditorInfo.IME_ACTION_SEARCH) {
                binding.includeIdentifyShelf.tvTargetShelfName.text = ""
                viewMode.getShelName(binding.includeIdentifyShelf.etTargetLocation.text.toString())
                false
            }
            false
        }
        binding.includeTile.rgTitle.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                binding.includeTile.rbTitleLeft.id -> {
                    changeViewStatus(true)
                }

                binding.includeTile.rbTitleRigh.id -> {
                    changeViewStatus(false)
                }
            }
        }

    }

    fun changeViewStatus(isSingleVolume:Boolean){
        binding.tvBookNum.visibility = if (isSingleVolume) View.VISIBLE else View.INVISIBLE
        viewMode._bookListData.postValue(listOf())
        binding.cbGetShelfNo.performClick()
        binding.includeIdentifyShelf.etSouceShelfNo.setText("")
        binding.includeIdentifyShelf.tvSouceShelfName.setText("")
        binding.includeIdentifyShelf.etTargetLocation.setText("")
        binding.includeIdentifyShelf.tvTargetShelfName.setText("")
        binding.includeIdentifyShelf.souceShelf.visibility =if (isSingleVolume) View.GONE else View.VISIBLE
        binding.includeIdentifyShelf.tvSouceShelfName.visibility = if (isSingleVolume) View.GONE else View.VISIBLE
        binding.includeIdentifyShelf.tvSouceLocation.visibility = if (isSingleVolume) View.GONE else View.VISIBLE
        binding.includeIdentifyShelf.etSouceShelfNo.visibility = if (isSingleVolume) View.GONE else View.VISIBLE
        binding.rvBookList.visibility =if (isSingleVolume) View.VISIBLE else View.GONE
        binding.includeBottom.cbAll.visibility = if (isSingleVolume) View.VISIBLE else View.GONE
        binding.includeTile.cbRignt.visibility = if (isSingleVolume) View.VISIBLE else View.GONE
    }

    override fun onResume() {
        super.onResume()
        observEven()
    }

    override fun onPause() {
        super.onPause()
        clearMsg()
        mScansManager?.stopScan()
    }

    override fun initViewModel(): BaseViewModel? {
        viewMode.bookListData.observe(viewLifecycleOwner){
            binding.tvBookNum.setText("数量：${it.size}")
            bookListAdapter.setNewData(it)

            var isAllSelet = true
            for (b in it){
                if (!b.isSelect){
                    isAllSelet = false
                    break
                }
            }
            binding.includeBottom.cbAll.isChecked = isAllSelet
        }
        viewMode.showMsg.observe(viewLifecycleOwner){
            ToastUtils.showShort(it)
            loadingDialog.hide()
        }
        viewMode.layerInfo.observe(viewLifecycleOwner){
            var content = "层架号：${it.outValue} \n名称：${it.name}"
            if (layerInfoSureDialog == null){
                layerInfoSureDialog = StandardDialog.newInstance()
            }
            if (binding.includeTile.rbTitleLeft.isChecked){
                layerInfoSureDialog!!.setTitle(getString(R.string.hint_sure_target_shelf))
                    .setContent(content)
                    .setOnDialogListener(object : StandardDialog.OnDialogClickListener {
                        override fun onConfirm(dialog: StandardDialog) {
                            binding.includeIdentifyShelf.tvTargetShelfName.setText(it.name)
                            binding.includeIdentifyShelf.etTargetLocation.setText(it.outValue)
                            binding.includeTile.cbRignt.performClick()
                            dialog.dismiss()
                        }

                        override fun onCancel(dialog: StandardDialog) {
                            dialog.dismiss()
                        }
                    })
            }else{
                layerInfoSureDialog!!
                    .setTitle(getString(R.string.hint_sure_source_target_shelf))
                    .setContent(content)
                    .setLeftText("来源位置")
                    .setRightText("目标位置")
                    .setOnDialogListener(object : StandardDialog.OnDialogClickListener {
                        override fun onConfirm(dialog: StandardDialog) {
                            binding.includeIdentifyShelf.tvTargetShelfName.setText(it.name)
                            binding.includeIdentifyShelf.etTargetLocation.setText(it.outValue)
                            newContainerSubId = it.id.toInt()
                            dialog.dismiss()
                        }

                        override fun onCancel(dialog: StandardDialog) {
                            binding.includeIdentifyShelf.tvSouceShelfName.setText(it.name)
                            binding.includeIdentifyShelf.etSouceShelfNo.setText(it.outValue)
                            srcContainerSubId = it.id.toInt()
                            dialog.dismiss()
                        }
                    })
            }
            if (!layerInfoSureDialog!!.isAdded){
                layerInfoSureDialog?.show(childFragmentManager)
            }
        }

        viewMode._bookInfoByBarcode.observe(viewLifecycleOwner){
            lifecycleScope.launch {
                viewMode.addBook(it)
            }
        }
        return viewMode
    }

    private fun onMessageChange(msgEvent: MsgEvent?) {
        when (msgEvent?.code){
            MsgCode.MSG_SCANS_BARCODE->{
                if (FastClickUtil.isFaskMsg(msgEvent.msg,200)) return //两次相同消息太快这不处理
                if (binding.cbGetShelfNo.isChecked){
                    viewMode.getShelName(msgEvent.msg)
                }
                if (binding.includeTile.cbRignt.isChecked){
                    val barcodeExists = viewMode._bookListData.value?.any { it.barCode == msgEvent.msg }
                    if (barcodeExists == true) return
                    viewMode.searchBookInfoByBarCode(msgEvent.msg)
                }
            }
        }
    }

    private fun observEven() {
        if (ApplicationViewModel.get().even != null) {
            if (ApplicationViewModel.get().even.hasObservers()) {
                ApplicationViewModel.get().even.removeObserver(observer)
            }
            ApplicationViewModel.get().even.observe(this,observer)
        }
    }
    fun clearMsg(){
        if (ApplicationViewModel.get().even != null) {
            if (ApplicationViewModel.get().even.hasObservers()) {
                ApplicationViewModel.get().even.removeObserver(observer)
            }
        }
    }
    @SuppressLint("WrongConstant")
    override fun initLoad() {
        var manager   = activity.getSystemService("scans")
        if (manager != null){
            mScansManager = manager as ScansManager
            mScansManager?.persistMode =true
        }
    }
}